<?php
	require('./common.php');
	$model = new Model('bbs_user');
	/*查询是否是注册的用户*/
	$_POST['username'] = trim(isset($_POST['username']) ? $_POST['username'] : '');
	$_POST['password'] = trim(isset($_POST['password']) ? $_POST['password'] : '');
	
	//判断用户名及密码是否是空
	if(empty($_POST['username']) || empty($_POST['password'])) {
		echo "<script>alert('用户名或密码不能为空!');window.history.back(-1);</script>";
		return;
	}
	$_POST['password'] = md5($_POST['password']);
	
	//判断验证码
	if(empty($_POST['code'])){
		echo "<script>alert('请输入验证码！');window.history.back(-1);</script>";
		return;
	} else {
		if($_POST['code'] != $_SESSION['code']) {
			echo "<script>alert('验证码输入错误！');window.history.back(-1);</script>";
			return;
		}
	}
	
	$name = $_POST['username'];
	$pass = $_POST['password'];
	
	$sqlfree1 = "SELECT * FROM `bbs_user` WHERE username = '{$name}' AND password='{$pass}'";
	$res = $model->free($sqlfree1);
	
	if($res){

		foreach ($res as $info) {}
		//验证密码
		if($info['password'] == $pass){
			/*验证权限*/
			if($info['qx'] == 1){
				setcookie('isLogin',1,time()+3600);
				setcookie('name',$name,time()+3600);
				setcookie('pic',$info['pic'],time()+3600);
				setcookie('qx',2,time()+3600);
				echo '<script>alert("登录成功");window.location.href="index.php";</script>';
			}else{
				/*用户无登录权限*/
				header('location:login.php?error=3');
			}
		}else{
			/*密码不正确*/
			header('location:login.php?error=2');
		}
		/*释放结果集资源*/
		mysqli_free_result($res);
	}else{
		/*用户名不存在*/
		header('location:login.php?error=1');
	}